import React, { FC } from 'react';
import {
  FormPanel,
  FormPanelType,
  RuleType,
  MinioUploadListType,
  type FormPanelObject,
  FormPanelStatus,
  InputType,
  FormPanelBtnAlign,
  FormPanelBtnDisplay,
  Utils
} from 'lfun-bg-comp';
import _ from 'lodash';
import './index.less';
import { Button, message } from 'antd';
import { useLocation, useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import {
  ECONOMIC_ATTRIBUTES,
  ETHNIC_ATTRIBUTES,
  SCHOOL_OPERATION_TYPE,
  SCHOOL_ORG_FORM,
  SCHOOL_ORG_TYPE,
  TOWN_NATURE,
} from '@/constant/schoolOptions';
import AddSchoolArea from './addSchoolArea';
import utils, { buildPageItemTxtByEduType, getPathRoot } from '@/utils';
import { openSchool, updateSchool } from '@/service/unit/school';
import { YES_NO } from '@/constant/basicOptions';
import ChangePopup from '@/view/component/changePopup';
import { LANGUAGE } from '@/constant/teachOptions';
import { getPlanningSchoolCategoryOptions, getPlanningSchoolOperationTypeOptions } from '@/service/options';
import OpenModal from '../component/openModal';
import useCountry from '@/hooks/useCountry';

// eslint-disable-next-line react/require-default-props
const Groups: FC<{ isEdit?: boolean; value?: any; buttons?: any[] }> = ({ isEdit = false, value, buttons = [] }) => {
  const navigate = useNavigate();
  const location = useLocation();
  //const [curForm, setCurForm] = React.useState<any>({});
  const [formPanelObject, setFormPanelObject] = React.useState<any>({});
  const [showChangePopup, setShowChangePopup] = React.useState(false);
  const [beforValue, setBeforValue] = React.useState<any>({});
  const [showOpenComfirm, setShowOpenComfirm] = React.useState(false);
  const country = useCountry();
  const [curvalue, setCurvalue] = React.useState<any>(value);

  React.useEffect(() => {
    if (value && /\d+/ig.test(value['school_communication.related_license_upload'])) {
      value['school_communication.related_license_upload'] = [{
        uid: parseInt(value['school_communication.related_license_upload']),
        url: value['school_communication.related_license_upload_url'],
        name: value['school_communication.related_license_upload_url'].split('?')[0],
      }]
    } else if (value){
      delete value['school_communication.related_license_upload'];
      delete value['school_communication.related_license_upload_url'];
    }
    setCurvalue(value);
    setBeforValue(value);
  }, [value]);
  const getObj = () => {
    const values = utils.unflattenObject(formPanelObject.getFieldsValue());
    const saveObj: any = { ...values };
    if (saveObj.school.founder_type) {
      saveObj.school.founder_type_lv2 = saveObj.school.founder_type[1];
      saveObj.school.founder_type_lv3 = saveObj.school.founder_type[2];
      saveObj.school.founder_type = saveObj.school.founder_type[0];
    }
    if (saveObj.school.school_operation_type) {
      saveObj.school.school_operation_type_lv2 = saveObj.school.school_operation_type[1];
      saveObj.school.school_operation_type_lv3 = saveObj.school.school_operation_type[2];
      saveObj.school.school_operation_type = saveObj.school.school_operation_type[0];
    }
    if (saveObj?.school?.create_school_date) {
      saveObj.school.create_school_date = dayjs(saveObj?.school?.create_school_date).format('YYYY-MM');
    }
    if (saveObj?.school?.school_closure_date) {
      saveObj.school.school_closure_date = dayjs(saveObj?.school?.school_closure_date).format('YYYY-MM-DD');
    }
    saveObj.school.id = location.state.id;
    return saveObj;
  };
  const save = async (hashmsg: any = true) => {
    utils.showLoading();
    const res = await updateSchool(location.state.id, getObj());
    if (res.success) {
      if (hashmsg) {
        message.success('修改成功');
      } else {
        return true;
      }
    } else {
      formPanelObject.reVaildation(res);
    }
    utils.hideLoaing(res.success);
    return false;
  };
  const list: FormPanelType[] = [
    {
      title: buildPageItemTxtByEduType('园所基本信息'),
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      inputs: [
        {
          label: buildPageItemTxtByEduType('园所名称'),
          name: 'school.school_name',
          key: 'school.school_name',
          required: true,
          canEdit: true,
          textRange: [0, 20],
        },
        {
          label: buildPageItemTxtByEduType('园所简称'),
          name: 'school.school_short_name',
          key: 'school.school_short_name',
          //required: true,
          textRange: [0, 10],
        },
        {
          label: buildPageItemTxtByEduType('园所英文名称'),
          name: 'school.school_en_name',
          key: 'school.school_en_name',
          //required: true,
          textRange: [0, 40],
        },
        {
          label: buildPageItemTxtByEduType('园所代码'),
          name: 'school.school_code',
          key: 'school.school_code',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '建校年月',
          name: 'school.create_school_date',
          key: 'school.create_school_date',
          required: true,
          inputProps: {
            picker: 'month',
          },
          inputType: InputType.date,
        },
        {
          label: '统一社会信用代码',
          name: 'school.social_credit_code',
          key: 'school.social_credit_code',
          required: true,
          inputType: InputType.text,
          textRange: [0, 18],
        },
        // {
        //   label: '学校性质',
        //   name: 'school.school_nature', //todo: 学校性质不是分三级的 学校性质：下拉框，必选，文本默认提示‘请选择’；内容：学前、初等、中等、高等
        //   key: 'school.school_nature',
        //   required: true,
        //   inputType: InputType.select,
        //   renderOption: SCHOOL_NATURE,
        // },
        {
          label: '城乡性质',
          name: 'school.urban_rural_nature',
          key: 'school.urban_rural_nature',
          required: true,
          inputType: InputType.cascader,
          renderOption: TOWN_NATURE,
          formatSubmitValue: (val: any) => {
            if (_.isArray(val)) return val.join(',');
            return val;
          },
          formatValue: (val: any) => {
            if (_.isString(val)) return val.split(',');
            return val;
          },
        },
        {
          label: '学校办别',
          name: 'school.school_org_type',
          key: 'school.school_org_type',
          required: true,
          disabled: true,
          inputType: InputType.select,
          renderOption: SCHOOL_ORG_TYPE,
        },
        {
          label: '办学组织形式',
          name: 'school.school_org_form',
          key: 'school.school_org_form',
          required: true,
          renderOption: SCHOOL_ORG_FORM,
          inputType: InputType.select,
        },
        {
          label: '教育层次',
          name: 'school.school_edu_level',
          key: 'school.school_edu_level',
          relationFields: ['school.school_category', 'school.school_operation_type'],
          required: true,
          disabled: true,
          inputType: InputType.select,
          renderOption: SCHOOL_OPERATION_TYPE,
        },
        {
          label: '学校（机构）类别',
          name: 'school.school_category',
          key: 'school.school_category',
          required: true,
          disabled: true,
          relationFields: ['school.school_operation_type'],
          inputType: InputType.select,
          renderOption: (form: FormPanelObject) => getPlanningSchoolCategoryOptions(form, 'school.school_edu_level'),
        },
        {
          label: '办学类型',
          name: 'school.school_operation_type',
          key: 'school.school_operation_type',
          required: true,
          disabled: true,
          inputType: InputType.select,
          renderOption: (form: FormPanelObject) =>
            getPlanningSchoolOperationTypeOptions(form, 'school.school_edu_level', 'school.school_category'),
        },
        // {
        //   label: '办学类型',
        //   name: 'school.school_operation_type',
        //   key: 'school.school_operation_type',
        //   required: true,
        //   disabled: true,
        //   renderOption: SCHOOL_OPERATION_TYPE,
        //   inputType: InputType.cascader,
        //   children: <Cascader />,
        // },
        // {
        //   label: '学校关闭日期',
        //   name: 'school.school_closure_date',
        //   key: 'school.school_closure_date',
        //   required: true,
        //   inputType: InputType.date,
        // },
        {
          label: '所在地经济属性',
          name: 'school.location_economic_attribute',
          key: 'school.location_economic_attribute',
          required: true,
          inputType: InputType.select,
          renderOption: ECONOMIC_ATTRIBUTES,
        },
        {
          label: '所在地民族属性',
          name: 'school.urban_ethnic_nature',
          key: 'school.urban_ethnic_nature',
          required: true,
          inputType: InputType.select,
          renderOption: ETHNIC_ATTRIBUTES,
        },
        {
          label: '法人证书号',
          name: 'school.leg_repr_certificatenumber',
          key: 'school.leg_repr_certificatenumber',
          required: true,
          textRange: [0, 50],
        },
        {
          label: '属地管理行政部门单位号',
          name: 'school.department_unit_number',
          key: 'school.department_unit_number',
          span: 10,
          required: true,
          textRange: [0, 20],
        },
        {
          label: '属地管理行政部门所在地地区',
          name: 'school.sy_zones',
          key: 'school.sy_zones',
          required: true,
          span: 14,
          inputType: InputType.select,
          renderOption: country,
        },
        {
          label: '历史沿革',
          name: 'school.historical_evolution',
          key: 'school.historical_evolution',
          required: true,
          span: 12,
          props: {
            labelCol: { span: 5 },
            wrapperCol: { span: 19 },
          },
          inputType: InputType.textarea,
          textRange: [0, 200],
        },
      ],
    },
    {
      title: buildPageItemTxtByEduType('园所通讯信息'),
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      inputs: [
        {
          label: '邮政编码',
          name: 'school_communication.postal_code',
          key: 'key_19',
          required: true,
          ruleType: RuleType.cnPostalCode,
        },
        {
          label: '传真电话',
          name: 'school_communication.fax_number',
          key: 'key_20',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '单位电子信箱',
          name: 'school_communication.email',
          key: 'key_21',
          ruleType: RuleType.email,
          required: true,
        },
        {
          label: '联系电话',
          name: 'school_communication.contact_number',
          key: 'key_22',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '电话区号',
          name: 'school_communication.area_code',
          key: 'key_23',
          required: true,
          textRange: [0, 10],
        },
        {
          label: '所在经度',
          name: 'school_communication.long',
          key: 'key_24',
          required: true,
          inputProps: {
            placeholder: '请输入所在经度 如经度123.4',
            allowClear: true,
          },
          textRange: [0, 10],
        },
        {
          label: '所在纬度',
          name: 'school_communication.lat',
          key: 'key_25',
          required: true,
          inputProps: {
            placeholder: '请输入所在纬度 如纬度41.7',
            allowClear: true,
          },
          textRange: [0, 10],
        },
        {
          label: '法定代表人姓名',
          name: 'school_communication.leg_repr_name',
          key: 'key_26',
          required: true,
          textRange: [0, 10],
        },
        {
          label: '党组织负责人姓名',
          name: 'school_communication.party_leader_name',
          key: 'key_27',
          required: true,
          textRange: [0, 10],
        },
        {
          label: '党组织负责人职务',
          name: 'school_communication.party_leader_position',
          key: 'key_28',
          required: true,
          textRange: [0, 10],
        },
        {
          label: '行政负责人姓名',
          name: 'school_communication.adm_leader_name',
          key: 'key_29',
          required: true,
          textRange: [0, 10],
        },
        {
          label: '行政负责人职务',
          name: 'school_communication.adm_leader_position',
          key: 'key_30',
          required: true,
          textRange: [0, 10],
        },
        {
          label: buildPageItemTxtByEduType('园所所在地区'),
          name: 'school_communication.loc_area',
          key: 'key_31',
          required: true,
          textRange: [0, 20],
        },
        {
          label: buildPageItemTxtByEduType('园所详细地址'),
          name: 'school_communication.detailed_address',
          key: 'school_communication.detailed_address',
          required: true,
          span: 16,
          props: {
            labelCol: {
              span: 4,
            },
            wrapperCol: { span: 20 },
          },
          inputType: InputType.textarea,
          textRange: [0, 100],
        },
        {
          label: '相关证照上传',
          name: 'school_communication.related_license_upload',
          key: 'key_33',
          required: false,
          inputType: InputType.minioUpload,
          inputProps: {
            listType: MinioUploadListType.picture,
            text: '浏览',
            maxCount: 1,
            uploadSrv: '/school/v1/storage/school-upload-uri',
          },
          formatSubmitValue: (value: any) => {
            if (_.isArray(value) && value.length) {
              return `${value[0].uid}`;
            }
            return '';
          }
          // formatValue: (value: any, record) => {
          //   if (value && record.related_license_upload_url) {
          //     return [{
          //       uid: record.related_license_upload,
          //       url: record.related_license_upload_url,
          //       name:record.related_license_upload_url,
          //     }];
          //   }
          //   return null;
          // },
        },
      ],
    },
    {
      title: buildPageItemTxtByEduType('园所教学信息'),
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      inputs: [
        {
          label: '是否民族校',
          name: 'school_eduinfo.is_ethnic_school',
          key: 'key_34',
          required: false,
          inputType: InputType.select,
          renderOption: YES_NO,
        },
        // {
        //   label: '是否附设班',
        //   name: 'school_eduinfo.is_att_class',
        //   key: 'key_35',
        //   required: true,
        //   inputType: InputType.select,
        //   relationFields: ['school_eduinfo.att_class_type'],
        //   renderOption: YES_NO,
        // },
        // {
        //   label: '附设班类型',
        //   name: 'school_eduinfo.att_class_type',
        //   key: 'key_36',
        //   required: true,
        //   inputType: InputType.select,
        //   renderOption: YES_NO,
        //   hidden: (formPanelObject: FormPanelObject) => {
        //     const values = formPanelObject.getFieldsValue();
        //     const tempRes =
        //       typeof formPanelObject.getFieldValue('school_eduinfo.is_att_class') === 'boolean'
        //         ? formPanelObject.getFieldValue('school_eduinfo.is_att_class')
        //         : values['school_eduinfo.is_att_class'];
        //     return tempRes !== true;
        //   },
        // },
        {
          label: '是否省特色',
          name: 'school_eduinfo.is_province_feat',
          key: 'key_37',
          required: false,
          inputType: InputType.select,
          renderOption: YES_NO,
        },
        {
          label: '是否具有双语教学班',
          name: 'school_eduinfo.is_bilingual_clas',
          key: 'key_38',
          required: true,
          inputType: InputType.select,
          relationFields: ['school_eduinfo.minority_lang_code'],
          renderOption: YES_NO,
        },
        {
          label: '少数民族语言编码',
          name: 'school_eduinfo.minority_lang_code',
          key: 'key_39',
          required: false,
          inputType: InputType.select,
          renderOption: LANGUAGE,
          hidden: (formPanelObject: FormPanelObject) => {
            const values = formPanelObject.getFieldsValue();
            const tempRes =
              typeof formPanelObject.getFieldValue('school_eduinfo.is_bilingual_clas') === 'boolean'
                ? formPanelObject.getFieldValue('school_eduinfo.is_bilingual_clas')
                : values['school_eduinfo.is_bilingual_clas'];
            return tempRes !== true;
          },
        },
        {
          label: '是否营利性',
          name: 'school_eduinfo.is_profitable',
          key: 'key_40',
          required: false,
          relationFields: ['school_eduinfo.prof_org_name'],
          inputType: InputType.select,
          renderOption: YES_NO,
        },
        {
          label: '营利性机构名称',
          name: 'school_eduinfo.prof_org_name',
          key: 'key_41',
          required: false,
          textRange: [0, 10],
          hidden: (formPanelObject: FormPanelObject) => {
            const values = formPanelObject.getFieldsValue();
            const tempRes =
              typeof formPanelObject.getFieldValue('school_eduinfo.is_profitable') === 'boolean'
                ? formPanelObject.getFieldValue('school_eduinfo.is_profitable')
                : values['school_eduinfo.is_profitable'];
            return tempRes !== true;
          },
        },
        {
          label: '是否省示范',
          name: 'school_eduinfo.is_prov_demo',
          key: 'key_42',
          required: false,
          inputType: InputType.select,
          renderOption: YES_NO,
        },
        {
          label: '是否最新年份',
          name: 'school_eduinfo.is_latest_year',
          key: 'key_43',
          required: false,
          inputType: InputType.select,
          renderOption: YES_NO,
        },
        {
          label: '是否乡镇幼儿园',
          name: 'school_eduinfo.is_town_kinderg',
          key: 'key_44',
          required: false,
          inputType: InputType.select,
          renderOption: YES_NO,
          hidden: Utils.getProps('edu_type') !== 'kg',
        },
        {
          label: '是否普惠性幼儿园',
          name: 'school_eduinfo.is_incl_kinderg',
          key: 'key_45',
          required: false,
          inputType: InputType.select,
          renderOption: YES_NO,
          hidden: Utils.getProps('edu_type') !== 'kg',
        },
        {
          label: '是否附属学校',
          name: 'school_eduinfo.is_affil_school',
          key: 'key_46',
          required: false,
          inputType: InputType.select,
          relationFields: ['school_eduinfo.affil_univ_code', 'school_eduinfo.affil_univ_name'],
          renderOption: YES_NO,
        },
        {
          label: '附属于高校（机构）标识码',
          name: 'school_eduinfo.affil_univ_code',
          key: 'key_47',
          hidden: (formPanelObject: FormPanelObject) => {
            const values = formPanelObject.getFieldsValue();
            const tempRes =
              typeof formPanelObject.getFieldValue('school_eduinfo.is_affil_school') === 'boolean'
                ? formPanelObject.getFieldValue('school_eduinfo.is_affil_school')
                : values['school_eduinfo.is_affil_school'];
            return tempRes !== true;
          },
        },
        {
          label: '附属高校（机构）名称',
          name: 'school_eduinfo.affil_univ_name',
          key: 'key_48',
          hidden: (formPanelObject: FormPanelObject) => {
            const values = formPanelObject.getFieldsValue();
            const tempRes =
              typeof formPanelObject.getFieldValue('school_eduinfo.is_affil_school') === 'boolean'
                ? formPanelObject.getFieldValue('school_eduinfo.is_affil_school')
                : values['school_eduinfo.is_affil_school'];
            return tempRes !== true;
          },
        },
        {
          label: '是否上年撤销',
          name: 'school_eduinfo.is_last_yr_revok',
          key: 'key_49',
          inputType: InputType.select,
          renderOption: YES_NO,
        },
        {
          label: '是否计校数',
          name: 'school_eduinfo.is_school_counted',
          key: 'key_50',
          inputType: InputType.select,
          renderOption: YES_NO,
        },
        {
          label: '小学学制',
          name: 'school_eduinfo.primary_school_system',
          key: 'school_eduinfo.primary_school_system',
          inputType: InputType.select,
          renderOption: [{
            label: '六年制',
            value: '6'
          }, {
            label: '五年制',
            value: '5'
          }],
          hidden: (formPanelObject: FormPanelObject) => {
            const values = formPanelObject.getFieldsValue();
            return !(values['school.school_edu_level'] === 'primaryEducation' // 所有初等教育
                  || values['school.school_operation_type'] === 'twelveYearSystemSchool' // 12年一贯制的
                  || values['school.school_category'] === 'secondaryVocationalSchool' // 中等职业学校
                  || values['school.school_edu_level'] === 'specialEducation' // 特殊教育
                  || values['school.school_edu_level'] === 'otherEducation' // 其他教育
                  || values['school.school_operation_type'] === 'nineYearSystemSchool'); // 9年一贯制的
          }
        },
        {
          label: '初中学制',
          name: 'school_eduinfo.junior_middle_school_system',
          key: 'school_eduinfo.junior_middle_school_system',
          inputType: InputType.select,
          renderOption: [{
            label: '三年制',
            value: '3'
          }, {
            label: '四年制',
            value: '4'
          }],
          hidden: (formPanelObject: FormPanelObject) => {
            const values = formPanelObject.getFieldsValue();
            return !(values['school.planning_school_operation_type'] === 'twelveYearSystemSchool' // 12年一贯制的
                    || values['school.planning_school_category'] === 'secondaryVocationalSchool' // 中等职业学校
                    || ['vocationalJuniorHigh',  // 职业初中
                        'adultJuniorHigh', // 成人初中
                        'workStudySchool', // 工读学校
                        'ordinaryJuniorHigh' // 普通初中
                      ].includes(values['school.planning_school_category'])
                    || values['school.planning_school_edu_level'] === 'specialEducation' // 特殊教育
                    || values['school.planning_school_edu_level'] === 'otherEducation') // 其他教育
                    ;
          }
        },
        {
          label: '高中学制',
          name: 'school_eduinfo.senior_middle_school_system',
          key: 'school_eduinfo.senior_middle_school_system',
          inputType: InputType.select,
          renderOption: [{
            label: '三年制',
            value: '3'
          }],
          hidden: (formPanelObject: FormPanelObject) => {
            const values = formPanelObject.getFieldsValue();
            return !([
                    'ordinaryHighSchool', // 普通高中
                    'adultHighSchool', // 成人高中
                    'secondaryVocationalSchool' // 中等职业学校
                  ].includes(values['school.school_category']) // 普通高中、成人高中、中等职业学校
                  || values['school.school_operation_type'] === 'twelveYearSystemSchool'
                  || values['school.school_edu_level'] === 'specialEducation' // 特殊教育
                  || values['school.school_edu_level'] === 'otherEducation') // 其他教育
                  ;
          }
        },
      ],
    },
    {
      title: '校区信息',
      inputs: [
        {
          label: '',
          name: 'school_area',
          key: 'key_51',
          span: 24,
          inputType: 'children',
          props: {
            labelCol: { span: 0 },
            wrapperCol: { span: 24 },
          },
          children: <AddSchoolArea isEdit={isEdit} />,
        },
      ],
    },
  ];
  const buildBtns = () => {
    return isEdit
      ? location.pathname.includes('/change/')
        ? [
            <Button key="import" loading={showChangePopup} onClick={() => setShowChangePopup(true)}>
              保存
            </Button>,
          ]
        : [
            <Button key="import" onClick={save}>
              保存
            </Button>,
          ]
      : buttons;
  };
  return (
    <div className={['opening', 'draft'].includes((value || {})['school.status']) ? '' : 'non-open-school'}>
      <ChangePopup
        show={showChangePopup}
        onCancel={() => setShowChangePopup(false)}
        onOk={async () => {
          const success = await save(false);
          setShowChangePopup(false);
          if (success) {
            setBeforValue(formPanelObject.getFieldsValue());
            message.success('变更成功');
          } else message.error('变更失败');
        }}
        beforValue={beforValue}
        form={formPanelObject}
        template={list}
      />
      <FormPanel
        template={list}
        key={1}
        onLoad={(formPanelObject: FormPanelObject) => {
          setFormPanelObject(formPanelObject);
        }}
        onFinishFailedDone={() => {
          document.querySelector('.ant-layout-content').scrollTop -= 80;
        }}
        onFinish={async (formPanelObject: FormPanelObject) => {
          // if (save(false)) {
          //   const res = await openSchool(location.state.id, getObj());
          //   if (res.success) {
          //     message.success('正式开办成功');
          //     navigate(`${getPathRoot()}/school`);
          //   } else {
          //     formPanelObject.reVaildation(res);
          //   }
          // }
          setShowOpenComfirm(true);
        }}
        values={curvalue}
        btnsAlign={FormPanelBtnAlign.center}
        buttonsDisplay={FormPanelBtnDisplay.block}
        restBtnText="返回"
        submitBtnText="正式开办"
        formStatus={isEdit ? FormPanelStatus.edit : FormPanelStatus.nonEdit}
        titleStyle="shrink"
        onReset={() => {
          navigate(`${getPathRoot()}/school`);
          return false;
        }}
        buttons={buildBtns()}
      />
      <OpenModal
        show={showOpenComfirm}
        onCancel={() => setShowOpenComfirm(false)}
        onOk={async (values: any) => {
          //if (save(false)) {
            const obj = getObj();
            obj.school.admin = values.admin;
            obj.school.admin_phone = values.admin_phone;
            const res = await openSchool(location.state.id, obj);
            if (res.success) {
              message.success('正式开办成功');
              navigate(`${getPathRoot()}/school`);
            } else {
              formPanelObject.reVaildation(res);
            }
          //}
        }}
      />
    </div>
  );
};

export default Groups;
